package com.sure.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sure.dao.GroupMapper;
import com.sure.exception.MyException;
import com.sure.pojo.Group;
import com.sure.utils.Config;
import com.sure.utils.Const;

@Service("GroupService")
public class GroupService {
	
	@Resource
	GroupMapper groupMapper;
	
	/**
	 * 获取组织列表
	 * @return
	 */
	public List<Group> getGroups(){
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		
		List<Group> groups;
		
		if(Config.getString("ADMINISTRATORS_USER_NAME", "admin").equals(session.getAttribute(Const.SESSION_USER_NAME))){ //超级管理员
			groups = groupMapper.queryGroups(null);
		}else{ //普通用户
			Group userGroup = groupMapper.selectByPrimaryKey((Integer) session.getAttribute(Const.SESSION_USER_GROUP_ID));
			Group param = new Group();
			param.setGroupPath(userGroup.getGroupPath());
			groups = groupMapper.queryGroups(param);
		}
		
		return groups;
	}
	
	/**
	 * 新增组织
	 * @param group
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public int addGroup(Group group) throws Exception{
		
		if(group.getGroupPid() == null || group.getGroupPid() <= 0){
			throw new MyException("缺少父节点");
		}
		
		Group parent = groupMapper.selectByPrimaryKey(group.getGroupPid());
		
		if(parent == null){
			throw new MyException("父节点ID错误");
		}
		
		groupMapper.insertSelectiveReturnId(group);
		
		group.setGroupPath(parent.getGroupPath() + group.getGroupId() + "|");
		
		return groupMapper.updateByPrimaryKeySelective(group);
	}
	
	/**
	 * 编辑组织
	 * @param group
	 * @return
	 * @throws Exception
	 */
	public int editGroup(Group group) throws Exception{
		
		return groupMapper.updateByPrimaryKeySelective(group);
	}
	
	/**
	 * 删除组织
	 * @param groupId
	 * @return
	 * @throws Exception
	 */
	public int delGroup(int groupId) throws Exception{
		Group param = new Group();
		param.setGroupPid(groupId);
		
		List<Group> children = groupMapper.queryGroups(param);
		
		if(children.size() > 0){
			throw new MyException("存在子组织,不能删除父组织");
		}
		
		return groupMapper.deleteByPrimaryKey(groupId);
	}
}
